<?

//Initiate Authenticate
SecurityRedirect ();

//echo"<pre>"; print_r($_POST);

//initiate Vars
define("PRIMARY_KEY","nobkt");
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
$FileName       = "ais_transaction_adventry_survey.php";
$FileTemplate   = "ais_transaction_adventry_survey_form.html";
$SubHeaderTitle = "Transaction Advance - Entry Advance From Survey";
$TableName          = "ais_advance";
$HTMLFormName   = "AdvanceForm";
$MaxGrid        = 20;
$KTRASL     = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
//$FormFields    = array("adv_id"=>"","urut"=>"0","uraian"=>"0","jumlah"=>"number");
$FormFields    = array("jo_id"=>"","jo_code"=>"","doc_ref"=>"","project_id"=>"","debtur"=>"", "qty_activity" => "","staff_id"=>"","jo_date"=>"date","jo_status"=>"");

//buildsqlfield ("$TableName", $FormFields);
//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);
$survey_id = GetParam("survey_id","");
$strError = "";
$errorStatus = "";
//echo"test: $jo_id";


//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
    if (GetParam("FormAction","")=="Save") {
        list($FDay,$FMonth,$FYear) = explode("/",GetParam("tglbkt",""));
        $tglbkt = "$FYear-$FMonth-$FDay";

        if (GetParam("curr","") == "USD"){
            $SQLGetKursTax = "SELECT * FROM ais_kurssi WHERE curr = 'USD' ORDER BY tglbkt DESC";
            $ResultGetKursTax  = $DBConnection->dbc->get_row($SQLGetKursTax,ARRAY_A);
            $rate = $ResultGetKursTax['rate'];
        } else {
            $rate = 1;
        }

        $rate    = StrToNumber (GetParam("rate",""));
        if (trim(GetParam("nobkt",""))=="AUTO NUMBERED BY SYSTEM")  {
            $ObjNumber  = new autonumber(GetParam("tglbkt",""));
            $TransNo = $ObjNumber->GetNumber("BS");
            //$kozhie = GetParam("debnam","");
            //echo "$TransNo $kozhie"; exit;
            //FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"debnam"=>GetParam("debnam",""),"nobkt"=>$TransNo,"tglbkt"=>"$tglbkt","curr"=>GetParam("curr",""),"kdact"=>GetParam("kdact",""),"noorder"=>GetParam("noorder",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"dk"=>"D","skada"=>GetBSParam(),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1","")),"adv_id");
            //FormSave("ais_advance", "qty_activity", array("jo_costing_id"=>"number", "services_id"=>"","activities_id"=>"","qty_activity"=>"", "qty_service"=>"", "job_costing_progress"=>"", "unit"=>"", "curr_activities"=>"", "rate_activities"=>"number", "amount"=>"number", "base_amount"=>"number", "tax_rate"=>"number", "tax_amount"=>"number", "total_amount"=>"number"), array("jo_id"=>$jo_id, "ledger"=>GetPeriod(GetParam("tglbkt","")), "nobkt"=>$TransNo, "tglbkt"=>"$tglbkt", "debtur"=>GetParam("debtur",""), "debnam"=>GetParam("debnam",""), "ktrasl"=>GetOfficeID()), "adv_id");


            for ($a=1;$a<=$MaxGrid;$a++){
                if(GetParam("services_id".$a,""))
                {
                    $service_id_buf =  GetParam("services_id".$a,"");
                    $service_name_buf =  GetParam("services_name".$a,"");
                    //echo ($service_name_buf); exit;

                    /*  
                    $SQLCheckAll = "SELECT * FROM ais_advance where jo_id = $jo_id AND services_id = $service_id_buf AND bs_progress = 'closed' ";
                    $ResultCheckAll = $DBConnection->dbc->query($SQLCheckAll);

                    if ($ResultCheckAll != 0){
                        $strError.= "-ND for service $service_name_buf already created or there's already closed BS \n";
                    }
                    */
                    
                    $SQLCheckJO = "SELECT * FROM tbljoactivity where jo_id = '".$jo_id."' AND services_id = '".$service_id_buf."' AND bill_nd = 'set' ";
                    $ResultCheckJO = $DBConnection->dbc->query($SQLCheckJO);
                   
                                       
                    if ($ResultCheckJO != 0){
						
                        $strError.= "This Service already set as prepared for ND Creation\nPlease unchecklist this service on module Job Order Preparation ND \n";
                        $errorStatus = "yes"; 
                             
                    }
                           
                    
                }
            }
            
            
            

            if(empty($errorStatus))
            {
				FormSave("ais_advance", "uraian", array("survey_act_id"=>"number","qty_activity" => "", "jumlah"=>"number", "curr"=>"", "uraian"=>""), array("survey_id" => $survey_id, "ledger"=>GetPeriod(GetParam("tglbkt","")), "nobkt"=>"$TransNo", "tglbkt"=>"$tglbkt", "debtur"=>GetParam("debtur",""), "debnam"=>GetParam("debnam",""), "ktrasl"=>GetOfficeID(), "bs_ref"=>"SURVEY", "rate"=>$rate, "bs_progress"=>"bs"), "adv_id");
				$DBConnection->InsertGrid();
		    }
            
            SetLogActivity($TransNo,"Create","");
        } else {
            $TransNo = GetParam("nobkt","");
            //FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"debnam"=>GetParam("debnam",""),"nobkt"=>$TransNo,"tglbkt"=>"$tglbkt","curr"=>GetParam("curr",""),"kdact"=>GetParam("kdact",""),"noorder"=>GetParam("noorder",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"dk"=>"D","skada"=>GetBSParam(),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1","")),"adv_id");
            //FormSave("ais_advance", "qty_activity", array("jo_costing_id"=>"number", "services_id"=>"","activities_id"=>"","qty_activity"=>"", "qty_service"=>"", "job_costing_progress"=>"", "unit"=>"", "curr_activities"=>"", "rate_activities"=>"number", "amount"=>"number", "base_amount"=>"number", "tax_rate"=>"number", "tax_amount"=>"number", "total_amount"=>"number"), array("jo_id"=>$jo_id, "ledger"=>GetPeriod(GetParam("tglbkt","")), "nobkt"=>$TransNo, "tglbkt"=>"$tglbkt", "debtur"=>GetParam("debtur",""), "debnam"=>GetParam("debnam",""), "ktrasl"=>GetOfficeID()), "adv_id");
            //$DBConnection->dbc->query("DELETE FROM ais_advance WHERE nobkt='$TransNo'");
            //FormSave("ais_advance", "uraian", array("jo_costing_id"=>"number", "jumlah"=>"number", "curr"=>"", "qty_activity"=>"number", "uraian"=>"", "skada"=>"", "services_id"=>"number"), array("jo_id"=>$jo_id, "ledger"=>GetPeriod(GetParam("tglbkt","")), "nobkt"=>"$TransNo", "tglbkt"=>"$tglbkt", "debtur"=>GetParam("debtur",""), "debnam"=>GetParam("debnam",""), "ktrasl"=>GetOfficeID(), "bs_ref"=>"SURVEY", "rate"=>$rate, "bs_progress"=>"bs"), "adv_id");
            FormSave("ais_advance", "uraian", array("survey_act_id"=>"number","qty_activity" => "", "jumlah"=>"number", "curr"=>"", "uraian"=>""), array("survey_id" => $survey_id, "ledger"=>GetPeriod(GetParam("tglbkt","")), "nobkt"=>"$TransNo", "tglbkt"=>"$tglbkt", "debtur"=>GetParam("debtur",""), "debnam"=>GetParam("debnam",""), "ktrasl"=>GetOfficeID(), "bs_ref"=>"SURVEY", "rate"=>$rate, "bs_progress"=>"bs"), "adv_id");
            $DBConnection->InsertGrid();
            SetLogActivity($TransNo,"Update","");
        }

//  UpdateHistory($TransNo,GetParam("total_trans",""));
    
    if(!empty($strError))  		  
    {
	   jsAlert($strError);	
    }

    DeleteRecord ("txtCheck",$MaxGrid);
    //header("Location: $FileName?PageMode=Form&nobkt=$TransNo");
    echo "Redirecting.... Please Wait.....";
    echo "<meta http-equiv='refresh' content='0;url=".$url."'>";
    exit;
    }

    if (GetParam("FormAction","")=="Cancel BS") {
//      print "Deleted"."<br>\n";
        //$SQL = "DELETE FROM ais_advance WHERE nobkt='".GetParam("nobkt","")."' ";
        $TransNo = GetParam("nobkt","");
        $SQL = "UPDATE ais_advance SET bs_progress = 'cancel' where nobkt = '$TransNo' ";
        $DBConnection->dbc->query($SQL);
        SetLogActivity(GetParam("nobkt",""),"Update","");
        header("Location: $FileName?PageMode=Form");
        exit;
    }

    if (GetParam("FormAction","")=="Delete") {
//      print "Deleted"."<br>\n";
        $SQL = "DELETE FROM ais_advance WHERE nobkt='".GetParam("nobkt","")."' ";
        $DBConnection->dbc->query($SQL);
        SetLogActivity(GetParam("nobkt",""),"Update","");
        header("Location: $FileName?PageMode=Form");
        exit;
    }

}

//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";
$VerifyFields = array("nobkt"=>"ID No.","tglbkt"=>"Transaction Date","curr"=>"Currency","kdact"=>"Activity Code","noorder"=>"");
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar,array("debtur"=>"Payment To"));

if (GetParam(PRIMARY_KEY,"")) {
    $SQLCount     = "SELECT count(*) FROM `$TableName`";
    $SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."'";
    $Count        = $DBConnection->dbc->get_var($SQLCount);
} else $Count=0;

$NewDataStart = $Count+1;
$InitFunction = "Masking();Masking2();";
$VerifyGrids = array("uraian"=>"0","jumlah"=>"number");
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("tglbkt"=>"date","rate"=>"number"),"2");
$JSMasks  = $Masking1.$Masking2;

Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);

//************ SET FORM MODE ***************
if (GetParam(PRIMARY_KEY,"")) {
  $FormMode = "Edit";
  $USER_CANPRINT="1";
  /*
  if (!isApproved(GetParam("nobkt",""))) $USER_CANPRINT="";
  else $USER_CANPRINT="1";*/
} else {
  $FormMode = "Add";
  $USER_CANPRINT="";
}

//******* DATABASE GRID QUERY ***********

//$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
/*$SQL = "SELECT * FROM `$TableName` a
        JOIN tbljoborder_costing z ON a.jo_costing_id = z.jo_costing_id
        JOIN tblservices b ON z.services_id = b.services_id
        JOIN tblactivity_nr c ON z.activities_id = c.act_nr_id ";*/

$SQL = "SELECT *, a.qty_activity as qty FROM `$TableName` a
        JOIN tblsurveyassgn_activity z ON a.survey_act_id = z.survey_act_id "
        ;

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
//echo "test";
    $SQLGrid  = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQLGrid .= " ORDER BY ".PRIMARY_KEY;
}
/*echo "test2 <br>";
$koz = GetParam($PRIMARY_KEY,"");
echo "$koz";
echo "$SQLGrid";
*/
//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************
//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Activity
$SQLAct  = "SELECT  * FROM tblactivity";
//Select TaxRate
$SQLTaxRate  = "SELECT  * FROM tbltaxrate where tax_group='cost' ORDER BY tax_id";
//Select Kurs Rate
$SQLGetKursTax = "SELECT * FROM ais_kurspjk WHERE curr = 'USD' ORDER BY tglbkt DESC";
$ResultGetKursTax  = $DBConnection->dbc->get_row($SQLGetKursTax,ARRAY_A);

$kursUSDTax = $ResultGetKursTax['rate'];

$HeaderFields = array("debnam"=>"0","nobkt"=>"0","tglbkt"=>"date","curr"=>"","rate"=>"number","debtur"=>"","kdact"=>"","app1"=>"","nmapp1"=>"","noorder"=>"");
//Leave Here Untouch
$FormCName     = BuildHTMLField($HeaderFields,"name",1);
$FormCValue    = BuildHTMLField($HeaderFields,"value",1);
/*
$SQLHeader     = "SELECT *, a.rate as adv_rate FROM $TableName a
                  JOIN tbljoborder_costing b ON a.jo_costing_id = b.jo_costing_id
                  JOIN tbljoborder c ON b.jo_id = c.jo_id ";
*/

$SQLHeader     = "SELECT *, a.rate as adv_rate FROM $TableName a
                  JOIN tblsurveyassgn b ON a.survey_id = b.survey_id 
                  JOIN tblproject as c ON b.project_id = c.project_id 
                  ";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= "WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);
$TBS->MergeBlock("receiptblk",$DBMysql,$SQLReceipt);
$TBS->MergeBlock("actblk",$DBMysql,$SQLAct);


// HTML Value
$TBS->MergeBlock("headbln",$FormCName);
if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
else $TBS->MergeBlock("headblv",$FormCValue);


//********************************* HTML GRID *********************************************

//GET Kurs
$SQLGetKurs = "SELECT * FROM ais_kurssi WHERE curr = 'USD' ORDER BY tglbkt DESC";
$ResultGetKurs  = $DBConnection->dbc->get_row($SQLGetKurs,ARRAY_A);

$kursUSD = $ResultGetKurs['rate'];
//END GET Kurs

//HTML Grid
if (strlen($SQLGrid)) $Result = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

//echo "<pre>";
//print_r($Result);


/*$SQLGridEntryAdvance =  "SELECT * FROM tbljoborder_costing a
                    JOIN tblservices b ON a.services_id = b.services_id
                    JOIN tblactivity_nr c ON a.activities_id = c.act_nr_id
                    WHERE a.jo_id = $jo_id";*/

$SQLGridEntryAdvance =  "SELECT * FROM $TableName a
                    WHERE a.jo_id = $jo_id";

//$ResultEntryAdvance  = $DBConnection->dbc->get_results($SQLGridEntryAdvance,ARRAY_A);
//$ResultEntryAdvance  = BuildEmptyGrid ($FormFields, $MaxGrid, $ResultEntryAdvance);

//$TBS->MergeBlock("blgEntryAdvance",$ResultEntryAdvance);
$TBS->MergeBlock("taxRate",$DBMysql,$SQLTaxRate);
$TBS->MergeBlock("deptblk",$DBMysql,$SQLDept);
$TBS->MergeBlock("blgEntryAdvance",$Result);

$TBS->Show();

//*************** ACTION FUNCTION *******************
function isApproved($nobkt) {
    global $DBConnection,$TableName;
        $SQL = "SELECT app1 FROM $TableName WHERE nobkt='$nobkt' limit 1";
        return $DBConnection->dbc->get_var($SQL);
}

function jsAlert($strError)
{
	$strError = str_replace("\n","\\n",$strError);
	
	echo '<script>
	      alert("'.$strError.'");	
	      </script>';
}

function FormInsert() {
    global $DBConnection,$FileName;
    $DBConnection->Insert();
    header("Location: $FileName?PageMode=Form");
    exit;
}

function FormUpdate() {
    global $DBConnection;
    $DBConnection->Update();
}

function FormDelete() {
    global $DBConnection,$FileName,$TableName;
    $DBConnection->deleteGrid("$TableName","nobkt");
    header("Location: $FileName?PageMode=Form");
    exit;
}

function FormSearch () {

}

function FormCancel () {
    global $FileName;
    header("Location: ".$FileName);
    exit;
}

function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey, $PrimaryKeyVal="") {
        global $FileName, $MaxGrid, $DBConnection, $jo_id, $strError;
        $TotalData = $MaxGrid * 2;
        $NewDataStart = GetParam("NewData","0");
        $NewDataStart = 1;



        for ($a=1;$a<=$TotalData;$a++) {

            //if (!GetParam("txtCheck".$a,"")) {

            if (GetParam($keyField.$a,"")) {

                $service_id = GetParam("services_id".$a,"");

                /*
                $SQLCheck = "SELECT * FROM ais_advance WHERE jo_id = $jo_id AND services_id=$service_id AND bs_progress='closed'";
                $ResultCheck = $DBConnection->dbc->query($SQLCheck);

                $strError = str_replace("\n","\\n", $strError);

                if ($ResultCheck != 0){
                    echo " <script>
                    alert('$strError');
                    </script>
                    ";
                    break;
                }
                */ 

                $survey_act_id = GetParam("survey_act_id".$a,"");

                $qty_activity = GetParam("qty_activity".$a,"");
                $qty_activity = intval($qty_activity);

                $qty_buffer = GetParam("qty_buffer".$a,"");
                $qty_buffer = intval($qty_buffer);

                $max_amount = GetParam("max_amount".$a,"");
                $max_amount = str_replace(",","",$max_amount);
                $max_amount = intval($max_amount);

                /*
                $rupiah = GetParam("rupiah".$a,"");
                $rupiah = str_replace(",","",$rupiah);
                $rupiah = intval($rupiah);

                $jumlah_buffer = GetParam("jumlah_buffer".$a,"");
                $jumlah_buffer = str_replace(",","",$jumlah_buffer);
                $jumlah_buffer = intval($jumlah_buffer);*/

                $jumlah = GetParam("jumlah".$a,"");
                $jumlah = str_replace(",","",$jumlah);
                $jumlah = intval($jumlah);

                if ($jumlah == "") {
                    $jumlah = 0;
                }


                if ($jumlah == $max_amount){
                    $SQLCosting = "UPDATE tblsurveyassgn_activity SET bs_status='Y'
                                WHERE survey_act_id = $survey_act_id";
                    $DBConnection->dbc->query($SQLCosting);
                }


                $qty_remain = $qty_buffer - $qty_activity;
                $budget_remain = $max_amount - $jumlah;
                //$amount_remain = $jumlah_buffer - $jumlah;

                //echo "$max_amount, $rupiah, $budget_remain"; exit;
                /*$SQLBudgetRemain = "UPDATE tbljoborder_costing SET budget_remain = $budget_remain, qty_activity_remain = $qty_remain, amount_remain = $amount_remain
                                WHERE jo_costing_id = $jo_costing_id";*/
                $SQLBudgetRemain = "UPDATE tblsurveyassgn_activity SET budget_remain = $budget_remain
                                WHERE survey_act_id = $survey_act_id";
                $DBConnection->dbc->query($SQLBudgetRemain);


                foreach ($FormFields as $key=>$formatting) {

                         //need advice
                         /*if (!GetParam($keyField.$a,"")) {
                                print GetParam($keyField.$a,"");
                                $EndOfData = 1;
                                break;
                         }*/
                         //need advice

                        if(!empty($PrimaryKeyVal))
                        {
                            $value = GetParam($key.$a,"");

                            if ($formatting=="number") $value = str_replace(",","",$value);
                            if ($formatting=="date")
                            {
                                    list($day,$month,$year) = explode("/",$value);
                                    $value = "$year-$month-$day";
                            }
                            //Inser if the key is equal primary key, then set valu = primary header
                            if($key == "$PrimaryKey")
                            {
                               $DBConnection->add_data($table,$key,$PrimaryKeyVal);
                            }

                            else
                            {
                               $DBConnection->add_data($table,$key,$value);
                            }

                        }

                        else
                        {
                            $value = GetParam($key.$a,"");

                            if ($formatting=="number") $value = str_replace(",","",$value);
                            if ($formatting=="date")
                            {
                                    list($day,$month,$year) = explode("/",$value);
                                    $value = "$year-$month-$day";
                            }

                            $DBConnection->add_data($table,$key,$value);

                        }

                }
                $rate = StrToNumber(GetParam("rate",""));
                $jmh  = StrToNumber(GetParam("jumlah".$a,""));
                $rupiah = $rate * $jmh;
                $DBConnection->add_data($table,"rupiah",$rupiah);

                //$rate = StrToNumber(GetParam("rate",""));
                //$jmh  = StrToNumber(GetParam("jumlah".$a,""));

                // Add by Chandra (15 May 2009)
                $cash_type = GetParam("cash_type","");
                //var_dump($cash_type); exit;



                if($cash_type) $DBConnection->add_data($table,'cash_type',$cash_type);
                // end update



                /*if ($EndOfData) {
                        break;
                }*/

                if (strlen($SpecialCase)) {
                        foreach ($SpecialCase as $key => $value) {
                                //print "add_data($table,$key,$value);<br>";
                                $DBConnection->add_data($table,$key,$value);

                        }
                }

//                print "$a < $NewDataStart<br>";
                if ($a < $NewDataStart) {
                         if (strlen($PrimaryKey)) {
                            $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
                          } else {
                            $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
                     }
                } else {
                        $DBConnection->InsertGrid();
//                        $DBConnection->dbc->debug();
                }
            }
        }

        $DBConnection->ClearData();
}
//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        for ($x=0;$x<count($arrayfield);$x++) {
            $DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
        }
}

function DeleteRecord ($sequence_name,$PageSize) {
    global $DBConnection,$FileName,$TableName;
    for ($x=1;$x<=$PageSize;$x++) {
        if (GetParam($sequence_name.$x,"")) {
            $DBConnection->deleteGrid("$TableName","adv_id",$sequence_name.$x);
        }
    }
}

function BuildFields ($FormFields) {
        global $DBConnection;
        $str = "";
        foreach ($FormFields as $key=>$formatting) {
            if (strlen($str)) $str .= ",$key";
            else $str = "$key";
        }
        return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
        global $DBConnection;
        $array_fields = array();
        for ($x=0;$x<$MaxGrid;$x++) {
            foreach ($FormFields as $key=>$formatting){
                $a=$x+1;
                $array_fields[$key.$a] = "$formatting";
            }
        }
        return $array_fields;
}

function UpdateHistory($nobkt,$value) {
    global $DBConnection;
    $SQL = "SELECT COUNT(*) FROM ais_history_trans WHERE entry1 = '".$nobkt."'";
    $isExist = $DBConnection->dbc->get_var($SQL);
    if ($isExist) {
        $DBConnection->dbc->query("UPDATE ais_history_trans SET amount1 = '".StrToNumber($value)."' WHERE entry1='".$nobkt."'");
    } else {
        $DBConnection->dbc->query("INSERT INTO ais_history_trans (ledger, ktrasl, entry1, amount1) VALUES ('".GetLedger()."','".GetOfficeID()."','$nobkt','".StrToNumber($value)."')");
    }
}
?>
